// 阅读器页面
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:ibook/appconfig/appconfig.dart';
import 'package:ibook/bookdetail/pageManager.dart';
import '../db/booksManager.dart';
import 'dart:convert';
import 'dart:collection';

class Reader extends StatefulWidget {
  // final List<Map<String, Object?>> content;
  final booksManager db;
  final String contengTableName;
  final List<Map<String, Object?>> firstChapter;
  final String bookName;
  final double width;
  final double height;
  Reader({Key? key, required this.firstChapter, required this.bookName, required this.db, required this.contengTableName, required this.width, required this.height}) : super(key: key);
  @override
  _ReaderPageState createState() => _ReaderPageState();
}

class _ReaderPageState extends State<Reader> {
  List<Map<String, Object?>> chapters = []; //章节内容
  final dimensions = AppConfig.dimensions; // 提前获取基础数据
  bool _isLoadingNextOptions = true; //用于控制底部栏的显示
  bool _isLoadingNextSettings = true; //用于控制设置弹窗的显示
  bool _isLoadingNextMenu = false; //用于控制菜单的显示
  final _pageManager = pageManager();
  String page = ""; //页面内容
  int i = 0;
  double fontSizevalue = 24; //用于控制字体大小
  Map<String, Object?> firstChapter = {};
  List<String> chapterMenu = []; //章节菜单
  late PageController _pageController;
  int _initialPage = 0;
  int currentPage = 0; //当前页
  int currentChapterID = 0; //当前章节ID
  Map<String, dynamic> bookmark = {}; //书签
  int _chapterNum = 0;
  List<String> pages = [];
  List<String> newPages = [];
  Map<String, Object?> combinedParams = {};
  List<String> oldPages = [];
  int pageStringLength = 0;
  String chapterName = "";
  // 添加类成员变量
  double cachedWidth = 0;
  double cachedHeight = 0;
  // 背景颜色列表
  List<String> reader_background = [
    "assets/images/ReadBG_1.jpg",
    "assets/images/ReadBG_2.jpg",
    "assets/images/ReadBG_3.jpg",
    "assets/images/ReadBG_4.jpg",
    "assets/images/ReadBG_5.jpg",
  ];
  String bgColor = "assets/images/ReadBG_1.jpg";
  // 添加目录滚动控制器
  final ScrollController _chapterScrollController = ScrollController();
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      firstChapter = widget.firstChapter[0];
      currentChapterID = firstChapter['id'] as int;
      final book = await widget.db.getBookInfo(widget.bookName);
      List<dynamic> dynamicList = jsonDecode(book[0]['catalogue'].toString());

      chapterMenu = dynamicList.cast<String>();
      // print("查询目录：${se[100]}");
      // 在调用分页前计算参数 firstChapter['chapter'].toString()
      // String testcontent = "国家" * 500;
      final Map<String, dynamic> params = {
        'content': firstChapter['chapter'].toString(),
        'fontSize': fontSizevalue,
        'pageWidth': dimensions['width']!,
        'pageHeight': dimensions['height']!,
        'lineHeightMultiple': 1.5 // 行高倍数
      };
      var pages = await PaginationWorker.paginate(params);
      setState(() {
        this.pages = pages;
      });
      _pageManager.addPages(pages, "", 0);
      setState(() {
        page = _pageManager.currentPage?.pageContent.toString() ?? "";
      });
      // print("pages: ${firstChapter}");
      _pageController = PageController(
        initialPage: _initialPage,
      );
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    cachedWidth = AppConfig.pageWidth; // 直接使用全局配置
    cachedHeight = AppConfig.pageHeight;
  }

  Future<void> _animateToFirstPageOfNewData(int targetPageIndex) async {
    await _pageController.animateToPage(
      targetPageIndex,
      duration: Duration(milliseconds: 100), // 自定义动画时长
      curve: Curves.easeOutBack, // 自定义动画曲线
    );
  }

  // *************************************加载下一章节
  Future<void> loadNextChapter() async {
    // 添加章节越界保护
    if (_chapterNum + 1 >= chapterMenu.length * .8) {
      print("已到达最后一章");
      return;
    }

    // final nextChapterContent = chapters[_chapterNum += 1]['chapter']?.toString() ?? '';
    _chapterNum += 1;
    final chapterCT = await widget.db.getBookContentInfo(widget.contengTableName, currentChapterID + 1, currentChapterID + 2);
    final nextChapterContent = chapterCT[0]['chapter'].toString() ?? '';

    currentChapterID++;

    newPages = await PaginationWorker.paginate({
      'content': nextChapterContent,
      'pageWidth': dimensions['width']!,
      'pageHeight': dimensions['height']!,
      'fontSize': fontSizevalue,
      'charsPerPage': combinedParams['charsPerPage'], // 确保传递计算参数
      'maxAdjustment': combinedParams['maxAdjustment']
    });

    if (mounted) {
      setState(() {
        // 如果到最后一页了，就清空pages，重新加载数据
        pages.clear();
        pages.addAll(newPages);
        chapterName = chapterMenu[_chapterNum - 1];
      });
      _pageManager.addPages(pages, chapterName, _chapterNum);
    }
  }

  // ****************************************加载上一章节
  Future<void> loadPrevChapter() async {
    // 添加章节越界保护
    if (_chapterNum - 1 < 0) {
      print("已到达第一章");
      return;
    }

    if (_chapterNum - 1 >= 0) {
      _chapterNum--;
      final chapterCT = await widget.db.getBookContentInfo(widget.contengTableName, currentChapterID - 1, currentChapterID);
      final nextChapterContent = chapterCT[0]['chapter'].toString() ?? '';
      currentChapterID--;
      oldPages = await PaginationWorker.paginate({
        'content': nextChapterContent,
        'pageWidth': dimensions['width']!,
        'pageHeight': dimensions['height']!,
        'fontSize': fontSizevalue,
        'charsPerPage': combinedParams['charsPerPage'], // 确保传递计算参数
        'maxAdjustment': combinedParams['maxAdjustment']
      });
    } else {
      print("已到达第一章");
      return;
    }
    setState(() {
      pages.clear();
      pages.addAll(oldPages);
      _pageController.animateToPage(
        oldPages.length - 1,
        duration: Duration(milliseconds: 1), // 动画时长
        curve: Curves.easeOut, // 动画曲线
      );
      if (_chapterNum - 1 >= 0) {
        chapterName = chapterMenu[_chapterNum - 1];
      } else
        chapterName = "";
    });
  }

  // 销毁阶段
  @override
  void dispose() {
    _pageController.dispose();
    bookmark = {'chapterID': currentChapterID, 'page': currentPage};
    // widget.db.updateBookInfo(widget.content[0]["id"].toString(), "bookmark", bookmark.toString());
    // print("销毁:book:$book")
    _chapterScrollController.dispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // 屏幕宽度
    final size = AppConfig.dimensions;
    final widthOfscreen = size['width']!;
    final heightOfscreen = size['height']!;

    // 底部栏弹窗
    Widget readerOptions() {
      return AnimatedPositioned(
          duration: Duration(milliseconds: 400),
          curve: Curves.elasticInOut,
          bottom: _isLoadingNextOptions ? -100 : 24,
          left: 0,
          right: 0,
          child: Stack(
            children: [
              Center(
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(20), // 圆角裁剪
                  child: BackdropFilter(
                    filter: ImageFilter.blur(sigmaX: 1, sigmaY: 1), // 模糊参数
                    child: AnimatedContainer(
                      duration: Duration(milliseconds: 400),
                      width: _isLoadingNextOptions ? widthOfscreen * .7 : widthOfscreen * .8,
                      height: _isLoadingNextOptions ? 50 : 75,
                      decoration: BoxDecoration(
                        color: Colors.white.withOpacity(0.1), // 半透明底色
                        borderRadius: BorderRadius.circular(20),
                        border: Border.all(color: Colors.white.withOpacity(.5), width: 1, style: BorderStyle.solid),
                        boxShadow: [
                          BoxShadow(
                            color: Color.fromARGB(255, 244, 248, 248).withOpacity(0.3),
                            blurRadius: 24,
                            spreadRadius: -1,
                          )
                        ],
                      ),
                    ),
                  ),
                ),
              ),
              Center(
                  child: ClipRRect(
                // 使边框变成圆角
                borderRadius: BorderRadius.circular(16),
                // 为组件添加动画
                child: AnimatedContainer(
                    duration: Duration(milliseconds: 400),
                    curve: Curves.easeInOut,
                    width: _isLoadingNextOptions ? widthOfscreen * .7 : widthOfscreen * .8,
                    height: _isLoadingNextOptions ? 50 : 75,
                    padding: EdgeInsets.all(12),
                    // color: Color.fromARGB(255, 113, 219, 210),
                    child: AnimatedOpacity(
                      duration: Duration(milliseconds: 400),
                      opacity: _isLoadingNextOptions ? 0.5 : 0.6,
                      curve: Curves.bounceInOut,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          FloatingActionButton(
                            heroTag: "menu",
                            onPressed: () {
                              setState(() {
                                _isLoadingNextMenu = !_isLoadingNextMenu;
                              });
                              if (!_isLoadingNextMenu) {
                                WidgetsBinding.instance.addPostFrameCallback((_) {
                                  _scrollToCurrentChapter();
                                });
                              }
                            },
                            backgroundColor: Colors.white.withOpacity(1),
                            foregroundColor: Colors.blue,
                            child: Icon(Icons.menu),
                            tooltip: "目录",
                          ),
                          FloatingActionButton(
                            heroTag: "font",
                            onPressed: () {},
                            backgroundColor: Colors.white.withOpacity(1),
                            foregroundColor: Colors.blue,
                            child: Icon(Icons.font_download),
                            tooltip: "字体",
                          ),
                          FloatingActionButton(
                            heroTag: "settings",
                            onPressed: () {
                              setState(() {
                                _isLoadingNextSettings = !_isLoadingNextSettings;
                              });
                            },
                            backgroundColor: Colors.white.withOpacity(1),
                            foregroundColor: Colors.blue,
                            child: Icon(Icons.settings),
                            tooltip: "设置",
                          ),
                          FloatingActionButton(
                            heroTag: "nightMode",
                            onPressed: () {},
                            backgroundColor: Colors.white.withOpacity(1),
                            foregroundColor: Colors.blue,
                            child: Icon(Icons.brightness_3),
                            tooltip: "夜间模式",
                          ),
                        ],
                      ),
                    )),
              ))
            ],
          ));
    }

    // 设置弹窗
    Widget settings() {
      return AnimatedPositioned(
          duration: Duration(milliseconds: 300),
          curve: Curves.fastOutSlowIn,
          bottom: _isLoadingNextSettings ? -300 : 120,
          left: 0,
          right: 0,
          child: Center(
              child: ClipRRect(
                  borderRadius: BorderRadius.circular(16),
                  child: AnimatedContainer(
                      duration: Duration(milliseconds: 100),
                      width: widthOfscreen,
                      height: 300,
                      color: Colors.white.withOpacity(.9),
                      child: Column(
                        children: [
                          // 背景颜色设置
                          Container(
                            width: widthOfscreen * .8,
                            margin: EdgeInsets.all(12),
                            height: 50,
                            child: ListView(
                              // mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              reverse: true,
                              scrollDirection: Axis.horizontal,
                              shrinkWrap: true,
                              children: [
                                ...reader_background.map((bg) {
                                  return GestureDetector(
                                      onTap: () {
                                        setState(() {
                                          bgColor = bg;
                                        });
                                      },
                                      child: Container(
                                        margin: EdgeInsets.only(right: 10),
                                        decoration: BoxDecoration(
                                            image: DecorationImage(
                                              image: AssetImage(bg), // 你的图片路径
                                              fit: BoxFit.cover, // 填充方式
                                              colorFilter: ColorFilter.mode(
                                                Colors.white.withOpacity(0.1), // 添加透明度确保文字可读
                                                BlendMode.dstOver,
                                              ),
                                            ),
                                            gradient: LinearGradient(
                                              colors: [
                                                Colors.white.withOpacity(0.4),
                                                Colors.white.withOpacity(0.1),
                                              ],
                                              begin: const Alignment(-1, -1),
                                              end: const Alignment(0.3, 0.5),
                                            ),
                                            borderRadius: BorderRadius.circular(5),
                                            boxShadow: [
                                              BoxShadow(
                                                color: const Color(0x000000).withOpacity(0.1),
                                                offset: const Offset(0, 1),
                                                blurRadius: 24,
                                                spreadRadius: -1,
                                              )
                                            ],
                                            border: Border.all(
                                              color: Colors.black,
                                              width: 1,
                                            )),
                                        child: ClipRRect(
                                          borderRadius: BorderRadius.circular(5),
                                          child: Container(
                                            width: 50,
                                            height: 50,
                                          ),
                                        ),
                                      ));
                                }).toList()
                              ],
                            ),
                          ),

                          // 字体大小设置
                          Container(
                            width: widthOfscreen * .8,
                            margin: EdgeInsets.all(12),
                            padding: EdgeInsets.all(10),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(5),
                              border: Border.all(
                                color: Colors.grey,
                                width: 1,
                              ),
                            ),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Container(
                                    width: widthOfscreen * .1,
                                    height: widthOfscreen * .1,
                                    child: GestureDetector(
                                      onTap: () {
                                        setState(() {
                                          if (fontSizevalue >= 13) {
                                            fontSizevalue -= 1;
                                          }
                                        });
                                      },
                                      child: Icon(Icons.remove),
                                    )),
                                Container(
                                    width: widthOfscreen * .5,
                                    height: widthOfscreen * .1,
                                    child: Material(
                                      child: Slider(value: fontSizevalue, min: 12.0, max: 32.0, activeColor: Colors.black, inactiveColor: Colors.blue, onChanged: _fontSizeChanged),
                                    )),
                                Container(
                                    width: widthOfscreen * .1,
                                    height: widthOfscreen * .1,
                                    child: GestureDetector(
                                      onTap: () {
                                        setState(() {
                                          if (fontSizevalue <= 31) {
                                            fontSizevalue += 1;
                                          }
                                        });
                                      },
                                      child: Icon(Icons.add),
                                    ))
                              ],
                            ),
                          ),

                          // 行距设置
                          Container(
                              width: widthOfscreen * .8,
                              margin: EdgeInsets.all(12),
                              padding: EdgeInsets.all(12),
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(5),
                                border: Border.all(
                                  color: Colors.grey,
                                  width: 1,
                                ),
                              ),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [Icon(Icons.density_large), Icon(Icons.density_medium), Icon(Icons.density_small)],
                              ))
                        ],
                      )))));
    }

    //目录弹窗
    Widget Menu() {
      return AnimatedPositioned(
          top: 0,
          left: _isLoadingNextMenu ? 0 : -(widthOfscreen / .8),
          duration: Duration(microseconds: 1000),
          child: Stack(
            children: [
              Container(
                  width: widthOfscreen / .8,
                  height: heightOfscreen / .8,
                  padding: EdgeInsets.only(left: 12, top: 70),
                  color: Color(0xffBED9DD),
                  child: ListView(controller: _chapterScrollController, children: [
                    // 章节列表
                    ...chapterMenu.asMap().entries.map((entry) {
                      final chapterIndex = entry.key; // 索引
                      final chapterName = entry.value; // 章节名称
                      return Center(
                          child: Container(
                        height: 40,
                        alignment: Alignment.centerLeft,
                        decoration: BoxDecoration(
                          border: Border(bottom: BorderSide(color: Colors.white, width: .1)),
                        ),
                        child: GestureDetector(
                            onTap: () {
                              print(chapterIndex);
                              // 跳转到指定章节
                              _navigateToChapter(chapterIndex + 1);
                            },
                            child: Text(
                              chapterName,
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.w500,
                                color: chapterMenu[currentChapterID - 1 >= 0 ? currentChapterID - 1 : currentChapterID] == chapterName ? Colors.blue[300] : Colors.black,
                                decoration: TextDecoration.none,
                              ),
                            )),
                      ));
                    }).toList()
                  ])),
              Positioned(
                  top: 0,
                  left: 0,
                  child: Container(
                    alignment: Alignment.center,
                    width: widthOfscreen / .8,
                    height: 100,
                    color: Color(0xffAECFD0),
                    padding: EdgeInsets.only(top: 40),
                    child: Text('目录',
                        style: TextStyle(
                          fontSize: 24,
                          fontWeight: FontWeight.w900,
                          color: Colors.black,
                          decoration: TextDecoration.none,
                        )),
                  )),
            ],
          ));
    }

    // 返回阅读器组件
    return Stack(children: [
      // 背景
      Positioned(
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        child: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage(bgColor), // 你的图片路径
              fit: BoxFit.cover, // 填充方式
              colorFilter: ColorFilter.mode(
                Colors.white.withOpacity(0.1), // 添加透明度确保文字可读
                BlendMode.dstOver,
              ),
            ),
          ),
          // color: bgColor,
          width: widthOfscreen,
          height: heightOfscreen,
        ),
      ),

      // 内容展示 如果内容不为空就渲染
      if (pages.isNotEmpty)
        GestureDetector(
          onDoubleTap: () {
            setState(() {
              _isLoadingNextOptions = !_isLoadingNextOptions;
            });
          },
          onPanEnd: (details) {
            setState(() {
              // 检测水平方向的移动
              //******************************* */ 向右滑，往前翻一页
              //******************************* */ 向右滑，往前翻一页
              //******************************* */ 向右滑，往前翻一页
              //******************************* */ 向右滑，往前翻一页
              if (details.velocity.pixelsPerSecond.dx > 0) {
                _isLoadingNextOptions = true; //关闭底部栏
                _isLoadingNextSettings = true;
                if (_pageManager.getCurrentPageIndex() == 0)
                  print("已经是第一页了");
                else {
                  final previousPage = _pageManager.previousPage();
                  page = previousPage?.pageContent.toString() ?? '';
                  chapterName = previousPage?.chapterName ?? '';
                }
                // 左滑，往后翻一页*****************************************************
                // 左滑，往后翻一页*****************************************************
                // 左滑，往后翻一页*****************************************************
              } else if (details.velocity.pixelsPerSecond.dx < 0) {
                _isLoadingNextOptions = true; //关闭底部栏
                _isLoadingNextSettings = true;
                if (_pageManager.getCurrentPageIndex() >= (_pageManager.length - 2)) {
                  loadNextChapter();
                }
                final nextpage = _pageManager.nextPage();
                page = nextpage?.pageContent ?? '';
                chapterName = nextpage?.chapterName ?? '';
              }
            });
          },
          child: // 在build方法中，包裹页面内容
              AnimatedSwitcher(
            duration: const Duration(milliseconds: 100),
            transitionBuilder: (Widget child, Animation<double> animation) {
              // 例如，一个淡入淡出和轻微平移的动画
              return FadeTransition(
                opacity: animation,
                child: SlideTransition(
                  position: Tween<Offset>(
                    begin: Offset(0.1, 0.0),
                    end: Offset.zero,
                  ).animate(animation),
                  child: child,
                ),
              );
            },
            child: KeyedSubtree(
              key: ValueKey(_pageManager.currentPage?.pageIndex),
              child: Container(
                  width: widthOfscreen,
                  height: heightOfscreen,
                  decoration: BoxDecoration(border: Border.all(width: 1, color: Color.fromARGB(255, 232, 238, 232)), boxShadow: [
                    BoxShadow(
                      color: const Color(0x000000).withOpacity(0.1),
                      offset: const Offset(0, 1),
                      blurRadius: 24,
                      spreadRadius: -1,
                    )
                  ]),
                  padding: EdgeInsets.only(left: 12, top: 70, right: 12, bottom: 12),
                  child: ConstrainedBox(
                      constraints: BoxConstraints(
                          maxWidth: widthOfscreen - 24, // 减去左右padding
                          maxHeight: heightOfscreen - 94 // 减去上下padding
                          ),
                      child: Text(
                        page,
                        textAlign: TextAlign.values[0],
                        maxLines: null,
                        style: TextStyle(
                          color: Colors.black,
                          fontSize: fontSizevalue,
                          fontWeight: FontWeight.w300,
                          decoration: TextDecoration.none,
                        ),
                      ))),
            ),
          ),
        ),

      // 章节名
      Positioned(
        top: 32,
        left: 24,
        right: 0,
        child: Container(
          width: widthOfscreen,
          height: 50,
          child: Text(
            chapterName,
            style: TextStyle(
              color: const Color.fromARGB(255, 20, 20, 20),
              fontSize: 16,
              decoration: TextDecoration.none,
            ),
          ),
        ),
      ),
      // 页数
      // Positioned(
      //   left: widget.width * 0.05,
      //   bottom: 10,
      //   child: Container(
      //     width: widthOfscreen,
      //     height: 50,
      //     child: Text(
      //       "${(currentPage + 1).toString()}/${pages.length.toString()}页",
      //       style: TextStyle(
      //         color: const Color.fromARGB(255, 20, 20, 20),
      //         fontSize: 12,
      //         fontWeight: FontWeight.normal,
      //         decoration: TextDecoration.none,
      //       ),
      //     ),
      //   ),
      // ),

      // // 按钮
      // Center(
      //     child: Opacity(
      //   opacity: 0,
      //   // 为子组件添加点击事件
      //   child: GestureDetector(
      //     child: Container(
      //       width: 100,
      //       height: 200,
      //       color: Color.fromARGB(255, 212, 211, 211),
      //     ),
      //     onTap: () {
      //       setState(() {
      //         _isLoadingNextOptions = !_isLoadingNextOptions;
      //         _isLoadingNextSettings = true;
      //       });
      //     },
      //   ),
      // )),

      // 设置弹窗
      settings(),
      //菜单弹窗
      Menu(),
      // 页面属性设置
      readerOptions(),
    ]);
  }

  void _fontSizeChanged(value) {
    setState(() {
      fontSizevalue = value;
    });
  }

  //跳转到目的章节
  void _navigateToChapter(int targetChapterId) async {
    // 关闭菜单
    setState(() {
      _isLoadingNextMenu = false;
    });

    // 如果目标章节就是当前章节，则无需操作
    if (targetChapterId == currentChapterID) {
      return;
    }

    final dimensions = AppConfig.dimensions;
    final Map<String, dynamic> params = {'fontSize': fontSizevalue, 'pageWidth': dimensions['width']!, 'pageHeight': dimensions['height']!, 'lineHeightMultiple': 1.5};

    // 计算近似字符数
    // 获取目标章节内容
    final chapterCT = await widget.db.getBookContentInfo(widget.contengTableName, targetChapterId, targetChapterId + 1);

    if (chapterCT.isEmpty) return;

    final targetChapterContent = chapterCT[0]['chapter'].toString();
    print("屏幕尺寸: ${dimensions['width']} x ${dimensions['height']}");

    // 分页处理
    final targetPages = await PaginationWorker.paginate({
      'content': targetChapterContent,
      'pageWidth': dimensions['width']!,
      'pageHeight': dimensions['height']!,
      'fontSize': fontSizevalue,
      'charsPerPage': combinedParams['charsPerPage'],
      'maxAdjustment': combinedParams['maxAdjustment']
    });

    // 更新状态
    setState(() {
      // 更新当前章节ID和索引
      currentChapterID = targetChapterId;
      _chapterNum = targetChapterId - 1;

      // 清空并更新页面内容
      pages.clear();
      pages.addAll(targetPages);

      // 更新章节名称
      if (_chapterNum >= 0 && _chapterNum < chapterMenu.length) {
        chapterName = chapterMenu[_chapterNum];
      } else {
        chapterName = "";
      }

      // 跳转到章节的第一页
      _pageController.jumpToPage(0);
    });
  }

  // 滚动到当前章节位置
  void _scrollToCurrentChapter() {
    if (_chapterScrollController.hasClients) {
      final itemHeight = 40.0;
      final currentChapterIndex = currentChapterID - 1;

      // 计算将当前章节置于中间位置所需的偏移量
      final targetPosition = currentChapterIndex * itemHeight - (_chapterScrollController.position.viewportDimension / 2) + (itemHeight / 2);

      // 执行滚动动画
      _chapterScrollController.animateTo(
        targetPosition.clamp(0.0, _chapterScrollController.position.maxScrollExtent),
        duration: Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
    }
  }
}

//********************************************************************************* */
// 后台处理分页操作
class PaginationWorker {
  // 移除 isolate 方式，直接在主线程进行精确分页
  static Future<List<String>> paginate(Map<String, dynamic> params) async {
    // 直接在主线程进行分页，因为需要使用 TextPainter
    return _paginateOnMainThread(params);
  }

  // 在主线程进行精确分页
  // 在主线程进行精确分页
  static List<String> _paginateOnMainThread(Map<String, dynamic> params) {
    final content = params['content'] as String;
    // 修改：实际可用宽度 = 屏幕宽度 - 左右边距(12+12)
    final pageWidth = (params['pageWidth'] as double) - 24;
    // 修改：实际可用高度 = 屏幕高度 - 上下边距(70+24)，再减去一些安全边距
    final pageHeight = (params['pageHeight'] as double) - 94 - 10; // 添加10像素安全边距
    final fontSize = params['fontSize'] as double;
    final lineHeightMultiple = (params['lineHeightMultiple'] as num?)?.toDouble() ?? 1.5;

    if (content.isEmpty) {
      return [];
    }

    List<String> pages = [];
    final textStyle = TextStyle(
      fontSize: fontSize,
      height: lineHeightMultiple,
    );

    // 使用TextPainter进行精确测量
    final textPainter = TextPainter(
      textDirection: TextDirection.ltr,
    );

    int startPos = 0;
    while (startPos < content.length) {
      // 使用更精确的方法找到最佳分页点
      int endPos = _findBestPageBreakImproved(content, startPos, pageWidth, pageHeight, textStyle, textPainter);

      // 防止无限循环
      if (endPos <= startPos) {
        endPos = startPos + 1;
      }

      // 优化分页点，尽量在语义合适的位置分页
      endPos = _optimizePageBreak(content, startPos, endPos);

      pages.add(content.substring(startPos, endPos));
      startPos = endPos;
    }

    textPainter.dispose();
    return pages;
  }

  // 查找最佳分页点
  // 改进的分页点查找算法
  static int _findBestPageBreakImproved(
    String content,
    int startPos,
    double pageWidth,
    double pageHeight,
    TextStyle textStyle,
    TextPainter textPainter,
  ) {
    // 从起始位置开始逐步测量文本
    int currentPos = startPos;
    double currentHeight = 0.0;

    while (currentPos < content.length) {
      // 尝试添加下一个字符
      int nextPos = _getNextWordBoundary(content, currentPos);

      // 如果已经到达内容末尾
      if (nextPos >= content.length) {
        return content.length;
      }

      // 测量添加这部分文本后的高度
      String testText = content.substring(startPos, nextPos);
      textPainter.text = TextSpan(text: testText, style: textStyle);
      textPainter.layout(maxWidth: pageWidth);

      // 如果添加这部分文本后超出了页面高度
      if (textPainter.height > pageHeight) {
        // 如果当前还没有任何文本被添加，至少添加一个字符
        if (currentPos == startPos) {
          currentPos = startPos + 1;
        }
        break;
      }

      currentPos = nextPos;
    }

    // 再进行一次优化确保不超出边界
    while (currentPos > startPos) {
      String testText = content.substring(startPos, currentPos);
      textPainter.text = TextSpan(text: testText, style: textStyle);
      textPainter.layout(maxWidth: pageWidth);

      if (textPainter.height < pageHeight) {
        break;
      }

      currentPos--;
    }

    return currentPos;
  }

  // 获取下一个词边界的位置
  static int _getNextWordBoundary(String content, int pos) {
    if (pos >= content.length) {
      return content.length;
    }

    // 对于中文文本，每个字符都是一个词边界
    // 对于英文文本，空格和标点符号是词边界
    int nextPos = pos + 1;

    // 如果是中文字符，返回下一个位置
    if (_isChinese(content.codeUnitAt(pos))) {
      return nextPos;
    }

    // 如果是英文字符，尝试找到单词结尾
    while (nextPos < content.length && !_isWhitespace(content.codeUnitAt(nextPos)) && !_isChinese(content.codeUnitAt(nextPos)) && !_isPunctuation(content.codeUnitAt(nextPos))) {
      nextPos++;
    }

    return nextPos;
  }

  // 判断是否为中文字符
  static bool _isChinese(int codeUnit) {
    return (codeUnit >= 0x4E00 && codeUnit <= 0x9FFF);
  }

  // 判断是否为空白字符
  static bool _isWhitespace(int codeUnit) {
    return (codeUnit == 0x0020 || // 空格
        codeUnit == 0x0009 || // 制表符
        codeUnit == 0x000A || // 换行符
        codeUnit == 0x000D); // 回车符
  }

  // 判断是否为标点符号
  static bool _isPunctuation(int codeUnit) {
    return (codeUnit >= 0x0021 && codeUnit <= 0x002F) || // ! " # $ % & ' ( ) * + , - . /
        (codeUnit >= 0x003A && codeUnit <= 0x0040) || // : ; < = > ? @
        (codeUnit >= 0x005B && codeUnit <= 0x0060) || // [ \ ] ^ _ `
        (codeUnit >= 0x007B && codeUnit <= 0x007E) || // { | } ~
        (codeUnit >= 0x3000 && codeUnit <= 0x303F) || // CJK符号和标点
        (codeUnit >= 0xFF00 && codeUnit <= 0xFFEF); // 全角ASCII、全角标点
  }

  // 优化分页点，尽量在句子结尾或段落结尾分页
  static int _optimizePageBreak(String content, int startPos, int breakPos) {
    // 如果已经在内容末尾，直接返回
    if (breakPos >= content.length) {
      return breakPos;
    }

    // 向前查找合适的断点（句子结尾或段落结尾）
    for (int i = breakPos; i > startPos; i--) {
      // 在句号、感叹号、问号后分页
      if (i > 0 && (content[i - 1] == '。' || content[i - 1] == '！' || content[i - 1] == '？' || content[i - 1] == '；')) {
        return i;
      }
      // 在换行符后分页
      if (i > 0 && content[i - 1] == '\n') {
        // 检查是否是段落结尾（连续两个换行符）
        if (i < content.length && content[i] == '\n') {
          return i + 1;
        }
        return i;
      }
    }

    // 没有找到更好的断点，返回计算出的位置
    return breakPos;
  }
}
